package edu.zut.cs.network.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import edu.zut.cs.network.base.BaseMainCase;
import edu.zut.cs.network.runnable.ServerRunnable;

public class Server extends BaseMainCase{
	private int port = 8821;
	private ServerSocket serverSocket;
	private ExecutorService executorService;
	private final int POOL_SIZE = 2;

	public Server() throws IOException {
		serverSocket = new ServerSocket(port);
		/*创建一个定长线程池，可控制线程最大并发数，超出的线程会在队列中等待*/
		executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE);
		/*Runtime.getRuntime().availableProcessors()获取cpu核心数*/
		logger.info("服务器启动时间:"+new Date());
	}

	public void service() {
		while (true) {
			Socket socket = null;
			try {
				socket = serverSocket.accept();
				executorService.execute(new ServerRunnable(socket));
				Thread.sleep(10000);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

